/**
 * Project Name:mobile_biz_cache
 * File Name:CacheRedisServiceImpl.java
 * Package Name:com.quwei.ds.mall.cache.service.impl
 * Date:2018年10月26日下午2:23:57
 * Copyright (c) 2018, Tu All Rights Reserved.
 *
*/

package com.steel.yfmall.cloud.assistant.common.impl;

import com.steel.yfmall.cloud.assistant.common.CacheRedisService;
import com.steel.yfmall.cloud.components.cache.RedisClient;
import com.steel.yfmall.cloud.components.cache.SerializableUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@Service
public class CacheRedisServiceImpl implements CacheRedisService {

	@Resource
	public RedisClient redisClient;

	private final static String SHARD_PREFIX = "STEEL_WAP_PRODUCT_REDIS";

	private Logger logger = Logger.getLogger(this.getClass());

	@Override
	public boolean setRedisData(String mark, int seconds, String strValue) {
		byte[] bytes = null;
		if (StringUtils.isBlank(mark)) {
			return false;
		}
		if (StringUtils.isNotBlank(strValue)) {
			try {
				bytes = SerializableUtils.getBytesFromObject(strValue);
			} catch (IOException e) {
				logger.error("function setUserObjData", e);
			}
			if (seconds <= 0) {
				redisClient.del(mark);
			} else {
				redisClient.setex(mark, seconds, bytes);
			}
		} else if (seconds <= 0) {
			redisClient.del(mark);
		}
		return true;
	}




	@Override
	public Object getCommonObjData(String markKey) {
		byte[] bytes = null;
		// 获取redis中的购物车信息
		bytes = redisClient.get(markKey.getBytes());
		Object base_data = null;
		if (bytes != null) {
			try {
				base_data = SerializableUtils.getObjectFromBytes(bytes, Object.class);
			} catch (Exception e) {
				logger.error("function getCommonObjData", e);

			}
		}
		return base_data;
	}

	@Override
	public String getCommonStringData(String markKeyString) {
		String returnString = "";
		if (StringUtils.isNotBlank(markKeyString)) {
			// 获取redis中的购物车信息
			byte[] bytes = redisClient.get(markKeyString.getBytes());
			if (bytes != null) {
				try {
					returnString = SerializableUtils.getObjectFromBytes(bytes, String.class);
				} catch (Exception e) {
					logger.error("function getCommonStringData", e);
				}
			}
		}
		return returnString;
	}

	@Override
	public boolean delCommonStringData(String markKeyString) {
		boolean result = false;
		if (StringUtils.isNotBlank(markKeyString)) {
			long flag= redisClient.del(markKeyString);
			if(flag > 0){
				return true;
			}
		}
		return result;
	}

	@Override
	public String generatorIndex(String prefix, Map<String, Serializable> params) {

		if (params == null || params.isEmpty()) {
            return null;
        }

		if (StringUtils.isBlank(prefix)) {
			prefix = SHARD_PREFIX;
		} else {
			prefix = SHARD_PREFIX + "_" + prefix;
		}

		Set<String> keyset = params.keySet();
		String[] a_keys = new String[keyset.size()];
		a_keys = keyset.toArray(a_keys);
		List<String> sortkeys = Arrays.asList(a_keys);
		StringBuffer sb = new StringBuffer("_");

		for (String sortkey : sortkeys) {
			sb.append(sortkey).append("=").append(params.get(sortkey)).append("&");
		}
		if (sb != null && sb.length() > 0) {
			sb.deleteCharAt(sb.length() - 1);
		}
		logger.debug("SecondRedisTemplate generatorIndex key content [" + sb.toString() + "]");
		return prefix + DigestUtils.md5Hex(sb.toString());
	}

	@Override
	public String generatorIndex(String prefix, String params) {

		if (params == null || params.isEmpty()) {
            return null;
        }

		if (StringUtils.isBlank(prefix)) {
			prefix = SHARD_PREFIX;
		} else {
			prefix = SHARD_PREFIX + "_" + prefix;
		}
		return prefix + "_" + DigestUtils.md5Hex(params);
	}

	@Override
	public boolean checkKeyExists(String markKeyString) {
		if(StringUtils.isBlank(markKeyString)){
			return false;
		}
		// 获取redis中的购物车信息
		return redisClient.exists(markKeyString);
	}

	@Override
	public boolean setRedisDataNoTime(String mark, String strValue) {
		byte[] bytes = null;
		if (StringUtils.isBlank(mark)) {
			return false;
		}
		if (StringUtils.isNotBlank(strValue)) {
			try {
				bytes = SerializableUtils.getBytesFromObject(strValue);
			} catch (IOException e) {
				logger.error("function setUserObjData", e);
			}
			redisClient.set(mark, bytes);
		}
		return true;
	}
}
